package service

import (
	"gobase/app/model"
	"gobase/util"

	"github.com/Sirupsen/logrus"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"github.com/xormplus/xorm"
)

type ResourceService struct {
	dao *xorm.Engine
	log *logrus.Logger
}

//初始化方法
func NewResourceService(c *gin.Context) *ResourceService {
	return &ResourceService{dao: util.GetDb(c), log: util.GetLog(c)}
}

//资源列表
func (srv *ResourceService) QueryList() []*model.Resource {
	db := srv.dao
	var resourceList []*model.Resource

	listSQL := "select t.* from resource as t order by parent_id asc,sortnum asc"
	//查询列表
	err := db.SQL(listSQL).Desc("t.id").Find(&resourceList)

	if err != nil {
		srv.log.Errorf("ResourceService->QueryList 列表查询错误：%s", err)
	}
	return resourceList
}

//获取顶部菜单
func (srv *ResourceService) GetNav(uid int64) []*model.Resource {
	var navList []*model.Resource
	orderBy := " order by t.parent_id asc,t.sortnum asc "

	if uid == 1 {
		navListSQL := "select t.id, t.title, t.category, t.url, t.`level`, t.parent_id from resource as t where t.parent_id=0 and t.category=1 " + orderBy
		srv.dao.SQL(navListSQL).Find(&navList)
	} else {
		navListSQL := "SELECT DISTINCT t.id, t.title, t.category, t.url, t.`level`, t.parent_id FROM resource AS t LEFT JOIN role_resource AS rr ON rr.resourceid = t.id LEFT JOIN role_user AS ru ON ru.roleid = rr.roleid LEFT JOIN role AS r ON r.id = ru.roleid WHERE t.parent_id = 0 AND t.category = 1 AND r.state = 1 AND ru.userid = ?"
		srv.dao.SQL(navListSQL, uid).Find(&navList)
	}
	return navList
}

//获取左菜单
func (srv *ResourceService) GetMenu(uid int64) []*model.Resource {
	var leftMenuList []*model.Resource
	orderBy := " order by t.parent_id asc,t.sortnum asc "

	if uid == 1 {
		menuListSQL := "select t.id, t.title, t.category, t.url, t.`level`, t.parent_id from resource as t where  t.parent_id<>0 and t.category in (1,2) " + orderBy
		srv.dao.SQL(menuListSQL).Find(&leftMenuList)
	} else {
		menuListSQL := "SELECT t.id, t.title, t.category, t.url, t.`level`, t.parent_id FROM resource AS t LEFT JOIN role_resource AS rr ON rr.resourceid = t.id LEFT JOIN role_user AS ru ON ru.roleid = rr.roleid LEFT JOIN role AS r ON r.id = ru.roleid WHERE t.parent_id > 0 AND t.category IN (1, 2) AND r.state = 1 AND ru.userid = ? " + orderBy
		srv.dao.SQL(menuListSQL, uid).Find(&leftMenuList)
	}
	return leftMenuList
}

//资源列表
func (srv *ResourceService) GetListNoFunc() []*model.Resource {
	db := srv.dao
	var resourceList []*model.Resource
	listSQL := "select t.* from resource as t where t.category<>3 order by parent_id asc,sortnum asc"
	//查询列表
	err := db.SQL(listSQL).Desc("t.id").Find(&resourceList)

	if err != nil {
		srv.log.Errorf("ResourceService->GetListNoFunc 列表查询错误：%s", err)
	}
	return resourceList
}

//新增资源
func (srv *ResourceService) Add(resource *model.Resource) error {
	//设置Level 值
	if resource.ParentId == 0 {
		resource.Level = 1
	} else {
		pResource, _ := srv.GetByID(resource.ParentId)
		resource.Level = pResource.Level + 1
	}

	_, err := srv.dao.Insert(resource)
	if err != nil {
		return errors.Wrap(err, "新增资源失败!")
	}
	return nil
}

//更新资源信息
func (srv *ResourceService) Update(id int, resource *model.Resource) error {
	//设置Level 值
	if resource.ParentId == 0 {
		resource.Level = 1
	} else {
		pResource, _ := srv.GetByID(resource.ParentId)
		resource.Level = pResource.Level + 1
	}

	_, err := srv.dao.Id(id).Cols("category,title,url,parent_id,sortnum,remark,icon,level").Update(resource)
	if err != nil {
		return errors.Wrap(err, "更新资源失败!")
	}
	return nil
}

//删除资源信息
func (srv *ResourceService) DeleteByID(id int) error {
	_, err := srv.dao.Id(id).Delete(new(model.Resource))

	if err != nil {
		return errors.Wrap(err, "删除资源失败!")
	}
	return nil
}

//根据ID查询一条记录,Map返回值
func (srv *ResourceService) GetMapByID(id int) (map[string]string, error) {
	var rMap = make(map[string]string)
	_, err := srv.dao.Sql("select t.Id, t.Category, t.Level, t.parent_id AS ParentId, t.Url, t.Title, t.Sortnum, t.Remark, t.Created, t.Updated,ifnull(p.Title,'') as ParentTitle from resource t left join resource as p on p.parent_id=t.id where t.id=?", id).Get(&rMap)
	if err != nil {
		return rMap, errors.Wrap(err, "获取资源map信息失败!")
	}
	return rMap, nil
}

//根据ID查询一条记录,Map返回值
func (srv *ResourceService) GetByID(id int) (model.Resource, error) {
	var resource model.Resource
	_, err := srv.dao.Sql("select t.* from resource as t where t.id=?", id).Get(&resource)

	if err != nil {
		return resource, errors.Wrap(err, "获取资源信息失败!")
	}
	return resource, nil
}
